package publisher

import (
	"encoding/json"
	"github.com/streadway/amqp"
	cfg "github.com/ufoscout/go-up"
	"go.uber.org/zap"
	"longmen/server/pkg/common/lib/rabbitmq"
)

type (
	PublishFansGroupServices struct {
		instance *rabbitmq.Producer // 发送实例
	}
)

// NewTxFansGroupPublish 开启一个生产实例
func NewTxFansGroupPublish(conf cfg.GoUp, rabbitConf rabbitmq.Config, publishName string, logger *zap.SugaredLogger) (*PublishFansGroupServices, error) {
	mq := rabbitmq.New(&rabbitConf, logger)
	c, queue, options := rabbitmq.GetRabbitProducerConfig(conf, publishName)
	producer, err := mq.NewProducer(c, queue, options)
	if err != nil {
		logger.Errorf("new producer err: %v", err)
		return nil, err
	}

	return &PublishFansGroupServices{
		instance: producer,
	}, nil
}

// BroadCast 广播消息
func (p *PublishFansGroupServices) BroadCast(msg interface{}) error {
	body, err := json.Marshal(msg)
	if err != nil {
		return err
	}
	return p.instance.Publish(amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		ContentType:  "application/json",
		Body:         body,
	})
}
